#include <iostream>

#include <cstdio>
#include <cstring>
#include <cstdlib>

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>
#include <signal.h>

#include "log.hpp"
#include "socket.hpp"
#include "Protocal.hpp"

Log log;

constexpr int RECV_SIZE = 1024;
pthread_t recvr, sender;

void* recv_message(void* args)
{
    const int* sockfd = static_cast<const int*>(args);
    std::string resp_stream;
    while (true)
    {
        char buffer[RECV_SIZE];
        //接收信息
        ssize_t n = read(*sockfd, buffer, RECV_SIZE - 1);
        if (n > 0)
        {
            buffer[n] = 0;
#ifdef __TEST_DEUBG__
            printf("server send: %s\n", buffer);
#endif
            resp_stream += buffer;
            while (true)
            {
                Response resp;
                if (resp.Deserialize(resp_stream))
                    std::cout << "result: " << resp._result << " exitcode: " << resp._exitcode << std::endl;
                else
                    break;
            }
        }
        else if (n == 0)
        {
            std::cout << "server is quit" << std::endl;
            pthread_cancel(sender);
            pthread_cancel(recvr);
        }
        else
        {
            std::cout << "write error, sockfd: " << *sockfd << ", errno: " << errno << ", errstring: " << strerror(errno) << std::endl;
            pthread_cancel(sender);
            pthread_cancel(recvr);
        }
    }
    return nullptr;
}
void* send_message(void* args)
{
    const int* sockfd = static_cast<const int*>(args);
    while (true)
    {
        Request req;
        std::cout << "Please Enter Cal(format: num oper num): ";
        scanf("%d%c%d", &req._left, &req._oper, &req._right);
        //发送信息
        std::string message;
        req.Serialize(message);
        int n = write(*sockfd, message.c_str(), message.size());
#ifdef __TEST__DEBUG__
        std::cout << "client send: " << message << std::endl;
#endif
        if (n < 0)
        {
            std::cout << "write error, sockfd: " << *sockfd << ", errno: " << errno << ", errstring: " << strerror(errno) << std::endl;
            pthread_cancel(recvr);
            pthread_cancel(sender);
        }
    }
    return nullptr;
}

void Usage(const std::string& proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n" << std::endl;
}
int main(int argc, char* argv[])
{
    signal(SIGPIPE, SIG_IGN);
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));
    // server.sin_addr.s_addr = inet_addr(serverip.c_str());
    socklen_t len = sizeof(server);
    
    while (true)
    {
        Socket socket;
        socket.Create(SOCK_STREAM);
        int sockfd = -1;
        // 连接服务器失败一定次数内重连
        int re_cnt = 10;
        bool re_connect = false;
        do
        {
            sockfd = socket.Connect((const struct sockaddr*)&server, len);
            if (sockfd < 0)
            {
                --re_cnt;
                std::cout << "connect error, reconnect: " << re_cnt << std::endl;
                re_connect = true;
                sleep(1);
            }
            else
                re_connect = false;
        } while (re_cnt && re_connect);
        if (re_cnt == 0)
        {
            std::cout << "user offline" << std::endl;
            exit(2);
        }

        pthread_create(&recvr, 0, recv_message, &sockfd);
        pthread_create(&sender, 0, send_message, &sockfd);

        pthread_join(recvr, nullptr);
        pthread_join(sender, nullptr);
        
        // std::cin.clear();
    }
    return 0;
}